package com.itheima.pinda.controller;


import com.itheima.pinda.DTO.entity.pojo.agency.PdAgencyScope;
import com.itheima.pinda.common.utils.IdWorker;
import com.itheima.pinda.DTO.entity.PdCoreOrg;
import com.itheima.pinda.feign.PdAgencyScopeFeign;
import com.itheima.pinda.service.PdCoreOrgService;
import com.itheima.pinda.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 组织 前端控制器
 * </p>
 *
 * @author xsf
 * @since 2021-11-11
 */
@RestController
@RequestMapping("/authority/org")
public class PdCoreOrgController {
    @Autowired
    private PdCoreOrgService pdCoreOrgService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private PdAgencyScopeFeign pdAgencyScopeFeign;

    @GetMapping("/tree")
    public List<PdCoreOrg> allTree(){
        List<PdCoreOrg> coreOrgList = pdCoreOrgService.queryAllTree();
//        System.out.println(coreOrgList);
        return coreOrgList;
    }
    @PostMapping
    public Result add(@RequestBody PdCoreOrg pdCoreOrg){
        long l = idWorker.nextId();
        pdCoreOrg.setId(l+"");
        boolean save = pdCoreOrgService.save(pdCoreOrg);

        //添加作业机构范围表
        if(save){
            List<PdAgencyScope> pdAgencyScopeList = pdCoreOrg.getPdAgencyScopeList();
            if(!CollectionUtils.isEmpty(pdAgencyScopeList)){
                pdAgencyScopeList.forEach(pdAgencyScope -> {
                    long id = idWorker.nextId();
                    pdAgencyScope.setAgencyId(pdCoreOrg.getId());
                    pdAgencyScope.setAreaId(pdCoreOrg.getCountyId().toString());
                    pdAgencyScope.setId(id+"");
                });
                Boolean aBoolean = pdAgencyScopeFeign.addPdAgencyScopes(pdAgencyScopeList);
            }
        }

        Result result = new Result(save, null);
        return result;
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Map<String,List<Long>> ids){
        List<Long> idList = ids.get("ids");
        boolean b =pdCoreOrgService.removeByIds(idList);
        Result result = new Result(b, null);
        return result;
    }
    @PutMapping
    public Result update(@RequestBody PdCoreOrg pdCoreOrg){
        boolean b = pdCoreOrgService.updateById(pdCoreOrg);
        return new Result(b, null);
    }

    @PostMapping("queryById")
    public PdCoreOrg update(@RequestParam String  id){
        PdCoreOrg coreOrg = pdCoreOrgService.getById(id);
        return coreOrg;
    }

}
